package hackathon.att.atl.android.autoresponder.GeoLocation;

import java.text.DecimalFormat;
import java.util.List;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;

public class GetLocationFromPhone implements Locator {
	private Context context;
	
	public GetLocationFromPhone(Context context){
		this.context = context;
	}

	@Override
	public String getLocation() {
		Location location = getLocationData();
		
		return (location == null) ? "" : latLongString(location); 
		
	}
	
	Location getLocationData(){
	    long minTime = 0;
	    long bestTime = 0;
	    float bestAccuracy = 20000000;
	    Location bestResult = null;

		LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); 
		List<String> matchingProviders = locationManager.getAllProviders();
		for (String provider: matchingProviders) {
		  Location location = locationManager.getLastKnownLocation(provider);
		  
		  if (location != null) {
		    float accuracy = location.getAccuracy();
		    long time = location.getTime();

		    if ((time > minTime && accuracy < bestAccuracy)) {
		      bestResult = location;
		      bestAccuracy = accuracy;
		      bestTime = time;
		    }
		    else if (time < minTime && 
		             bestAccuracy == Float.MAX_VALUE && time > bestTime){
		      bestResult = location;
		      bestTime = time;
		    }
		  }
		}
		
		return bestResult;
	}
	
	String latLongString(Location location){
		DecimalFormat format = new DecimalFormat("#.####");
		
		String latitude = format.format( location.getLatitude() );
		String longitude = format.format( location.getLongitude() );
		
		return latitude + "," + longitude;
	}

}
